package com.bianmaba.spring.security.handler;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class AjaxGlobalExceptionHandler extends AbstractAjaxHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AjaxGlobalExceptionHandler.class);

    @ExceptionHandler({Exception.class, RuntimeException.class})
    public void handleException(HttpServletResponse response, Exception e) throws IOException {
        Map<String, Object> result = new HashMap<String, Object>(0);
        result.put("success", false);
        result.put("status", 500);
        result.put("statusText", e.getLocalizedMessage());
        result.put("SecurityMessage", true);
        result.put("result", "资源请求失败，请求的资源出现异常！");
        result.put("failureType", e.getClass().getSimpleName());
        result.put("exception", ExceptionUtils.getStackTrace(e));
        writeAjax(response, result, 500);
        LOGGER.error(result.get("result").toString(), e);
    }
}
